﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace com.kmxy.MonitorModel
{
    /// <summary>
    /// 进程操作的相关方法
    /// </summary>
    public class ProcessUtility
    {

        /// <summary>
        /// 检测进程是否存在
        /// </summary>
        /// <param name="procName"></param>
        /// <returns></returns>
        public static bool CheckProcExists(string procName, out string lastState)
        {
            lastState = string.Empty;
            try
            {
                var pn = procName.ToLower().Replace(".exe", "").Trim();
                var procs = Process.GetProcesses();
                var x = from l in procs where l.ProcessName.ToLower() == pn select l;
                if (x.Any())
                    return true;

            }
            catch (Exception e)
            {
                lastState = $"检测进程{procName}是否存在时出现异常:{e.Message}";
            }
            return false;
        }

        /// <summary>
        /// 启动指定的进程
        /// </summary>
        /// <param name="model">进行模块</param>
        /// <returns></returns>
        public static bool StartProcess(ProcModel model, out string lastState)
        {
            lastState = string.Empty;
            bool st;
            try
            {
                var filePath = model.Path + model.Name;
                if (!File.Exists(filePath))
                {
                    lastState = $"应用程序=> {filePath} 文件不存在，已放弃对此进程的加载！";
                    return false;
                }
                var ps = new ProcessStartInfo(filePath, model.Args);
                //ProcessStartInfo ps = new ProcessStartInfo(model.Name, model.Args);
                ps.WorkingDirectory = model.WorkPath;
                ps.ErrorDialog = true;
                //ps.Verb = "runas";//设置启动动作，确保以管理员方式运行
                ps.WindowStyle = ProcessWindowStyle.Hidden;
                ps.CreateNoWindow = true;
                ps.RedirectStandardError = false;
                ps.RedirectStandardInput = false;
                ps.RedirectStandardOutput = false;

                var p = new Process { StartInfo = ps };
                st = p.Start();
                lastState = st ? $"启动进程=> {model.Name}成功,进程ID:{p.Id}" : $"启动进程=> {model.Name}失败！";
            }
            catch (Exception e)
            {
                lastState = $"启动进程=> {model.Name}时出现异常：{e.Message}";
                return false;
            }
            return st;
        }
        /// <summary>
        /// 关闭指定的进程
        /// </summary>
        /// <param name="ProName"></param>
        public static bool KillProcess(string ProName, out string lastState)
        {
            lastState = string.Empty;
            var ste = false;

            var pn = ProName.ToLower().Replace(".exe", "").Trim();
            var allPorcess = Process.GetProcesses();
            var processes = from m in allPorcess where m.ProcessName.ToLower() == pn select m;
            if (processes != null && processes.Any())
                foreach (var item in processes)
                {
                    try
                    {
                        item.Kill();
                        lastState = $"进程=> {ProName} 关闭正常！";
                        ste = true;
                    }
                    catch (Exception e)
                    {
                        lastState = $"进程=> {ProName} 关闭时出现异常：{e.Message}";
                    }
                }
            else
                lastState = $"进程=> {ProName} 未找到此进程！";

            return ste;
        }
    }
}
